﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using Couchbase.Core.IO.Operations;
using HDSmartCommunity.BUS;
using HDSmartCommunity.DAL;
using HDSmartCommunity.Models;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using Timer = System.Timers.Timer;

namespace HDSmartCommunity.DevicePlatform
{
    public class HDDeviceSerialData
    {
        public List<int> phy_list = new List<int>();//物理楼层列表
        public List<string> show_list = new List<string>();//显示楼层列表
        public List<int> act_list = new List<int>();//实际楼层列表
        public string oldstatus_1 = string.Empty;//电梯上一次状态
        public int liftid = 0;//梯号
        public static int ele_control = -1;//查询状态中梯控模式的值
        public static int face_device_status = 0;//人脸设备状态，0=设备断开，1=设备连接
        public bool TcpAuthorize = false;//恒大平台是否下发进入梯控
        public bool ismaster = false;//是否主梯
        public MemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions() { });//电梯状态缓存
        public string StatusCmd = string.Empty;//电梯状态命令
        public static DateTime statussend;//副梯发送状态时间
        public static List<string> cmdlist = new List<string>();//发送命令队列
        public int sign_kt = -1;
        public static int Elevatormode = -1;//电梯工作模式,0梯控，1普通
        public int count = 1;//流水号
        public string devid;//主设备ID
        public string subdevid;//子设备ID

        public bool hd_server_flag = false;//恒大平台连接
        public bool device_register_flag = false;//设备注册
        public Socket server;
        public DevInfo devinfo;
        public Thread thread;
        public ParameterRead Parameter = new ParameterRead();
        public string version_1 = "";
        public Dictionary<int, List<byte>> dic_data = new Dictionary<int, List<byte>>();
        public int reporttime = 0;
        public int hd_kt = -1;
        public int light = -1;

        #region 访客联动
        public SerialPort myS0SerialPort_1 = new SerialPort();
        private Timer SerialPortRecvTimerS0_1;
        private static int pSerialPortRecv_S0_1 = 0;
        private static int byteLength = 40960;
        public byte[] byteSerialPortRecvS0_1 = new byte[byteLength];
        public event EventHandler<SerialPort485_1RecvEventArgs> ReceivedDataEventS0_1;
        public void OpenS0SerialPort(string portName, int baudRate, int parity, int dataBits, int stopBits)
        {
            try
            {
                SetS0SerialPortConfig(portName, baudRate, parity, dataBits, stopBits);
                myS0SerialPort_1.Open();
                LogHelper.Log(portName + "打开成功");

            }
            catch (Exception e)
            {
                LogHelper.Log("ttyS0打开异常" + e.ToString());
            }
        }

        private void SetS0SerialPortConfig(string portName, int baudRate, int parity, int dataBits, int stopBits)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                portName = $"/dev/{portName}";
            }
            // 串口 参数设置
            myS0SerialPort_1.PortName = portName;
            myS0SerialPort_1.BaudRate = baudRate;
            switch (parity)
            {
                case 0:
                default:
                    myS0SerialPort_1.Parity = Parity.None;
                    break;
                case 1:
                    myS0SerialPort_1.Parity = Parity.Odd;
                    break;
                case 2:
                    myS0SerialPort_1.Parity = Parity.Even;
                    break;
                case 3:
                    myS0SerialPort_1.Parity = Parity.Mark;
                    break;
                case 4:
                    myS0SerialPort_1.Parity = Parity.Space;
                    break;
            }
            myS0SerialPort_1.DataBits = ((4 < dataBits) && (dataBits < 9)) ? dataBits : 8;
            switch (stopBits)
            {
                case 0:
                    myS0SerialPort_1.StopBits = StopBits.None;
                    break;
                case 1:
                default:
                    myS0SerialPort_1.StopBits = StopBits.One;
                    break;
                case 2:
                    myS0SerialPort_1.StopBits = StopBits.OnePointFive;
                    break;
                case 3:
                    myS0SerialPort_1.StopBits = StopBits.Two;
                    break;
            }
            //my485SerialPort_1.ReadTimeout = 200;
            myS0SerialPort_1.RtsEnable = true;
            myS0SerialPort_1.DataReceived += new SerialDataReceivedEventHandler(DataReceived_ttyS0);

            // 串口 接收数据处理定时器 参数设置
            SerialPortRecvTimerS0_1 = new System.Timers.Timer();
            SerialPortRecvTimerS0_1.Interval = 100;
            SerialPortRecvTimerS0_1.AutoReset = false;
            SerialPortRecvTimerS0_1.Elapsed += new ElapsedEventHandler(SPRecvTimer_Tick_ttyS0_1);
        }

        private void SPRecvTimer_Tick_ttyS0_1(object sender, EventArgs e)
        {
            byte[] TemporaryData = new byte[byteLength];
            int TemporaryDataLength = 0;

            if (ReceivedDataEventS0_1 != null)
            {
                byteSerialPortRecvS0_1.CopyTo(TemporaryData, 0);
                TemporaryDataLength = pSerialPortRecv_S0_1;

                ReceivedDataEventS0_1.Invoke(this, new SerialPort485_1RecvEventArgs(TemporaryData, TemporaryDataLength));
                // 数据处理完后，将指针指向数据头，等待接收新的数据
                pSerialPortRecv_S0_1 = 0;
            }
        }

        public class SerialPort485_1RecvEventArgs : EventArgs
        {
            /// <summary>
            /// 广播 收到的串口数据
            /// </summary>
            public readonly byte[] RecvData_485_1 = new byte[byteLength];

            /// <summary>
            /// 收到数据 的 长度
            /// </summary>
            public readonly int RecvDataLength_485_1;

            /// <summary>
            /// 将 收到的数据 转化成 待广播的数据
            /// </summary>
            public SerialPort485_1RecvEventArgs(byte[] recvData, int recvDataLength)
            {
                recvData.CopyTo(RecvData_485_1, 0);
                RecvDataLength_485_1 = recvDataLength;
            }
        }

        private void DataReceived_ttyS0(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                SerialPortRecvTimerS0_1.Stop();

                byte[] ReadBuf = new byte[myS0SerialPort_1.BytesToRead];
                if (pSerialPortRecv_S0_1 > byteLength - ReadBuf.Length)
                {
                    pSerialPortRecv_S0_1 = 0;
                }
                myS0SerialPort_1.Read(ReadBuf, 0, ReadBuf.Length);
                ReadBuf.CopyTo(byteSerialPortRecvS0_1, pSerialPortRecv_S0_1);
                pSerialPortRecv_S0_1 += ReadBuf.Length;
                SerialDataSaveLogHelper.Log("ttys0_receive:" + ToHexs(ReadBuf));
                try
                {
                    for (int i = 0; i < byteSerialPortRecvS0_1.Length; i++)
                    {
                        if (byteSerialPortRecvS0_1[i] == liftid && byteSerialPortRecvS0_1[i + 1] == 0x10 && byteSerialPortRecvS0_1[i + 5] == 0x05)
                        {
                            string strCmd = string.Empty;
                            byte[] buffers = new byte[8];
                            for (int j = 0; j < 8; j++)
                            {
                                buffers[j] = byteSerialPortRecvS0_1[i + j];
                            }

                            int length = buffers.Length;
                            byte[] crcdata = new byte[length - 2];
                            for (int k = 0; k < length - 2; k++)
                            {
                                crcdata[k] = buffers[k];
                            }
                            byte[] crc = Crc18(crcdata);
                            if (crc[0] == buffers[length - 1] && crc[1] == buffers[length - 2])
                            {
                                Array.Clear(byteSerialPortRecvS0_1, i, buffers.Length);
                                //TmpDataReceived.AddRange(buffers);
                                //LogHelper.Log("命令回复" + ToHexs(buffers));
                            }
                        }
                        else if (byteSerialPortRecvS0_1[i] == liftid && byteSerialPortRecvS0_1[i + 1] == 0x03 && byteSerialPortRecvS0_1[i + 2] == 8)
                        {
                            string data = string.Empty;
                            string strCmd = string.Empty;
                            int numcount = Convert.ToInt32(byteSerialPortRecvS0_1[i + 2]);
                            byte[] buffers = new byte[numcount + 5];
                            for (int j = 0; j < numcount + 5; j++)
                            {
                                buffers[j] = byteSerialPortRecvS0_1[i + j];
                            }

                            int length = buffers.Length;
                            byte[] crcdata = new byte[length - 2];
                            for (int k = 0; k < length - 2; k++)
                            {
                                crcdata[k] = buffers[k];
                            }
                            byte[] crc = Crc18(crcdata);
                            if (crc[0] == buffers[length - 1] && crc[1] == buffers[length - 2])
                            {
                                Array.Clear(byteSerialPortRecvS0_1, i, buffers.Length);

                                byte[] status = buffers.Skip(3).Take(8).ToArray();
                                string newstatus = ToHexs(status);
                                if (newstatus != oldstatus_1)//状态与上一次不一致
                                {
                                    //解析电梯状态数据
                                    LogHelper.Log("电梯状态点：" + newstatus);
                                    HDZHCurrentElevatorStatus elevatorPoint = ParsingData(liftid, buffers);

                                    if (TcpAuthorize)
                                    {
                                        if (ele_control == 0 && face_device_status == 1)//电梯梯控状态与上一次断开前状态不一致
                                        {

                                            LogHelper.Log("当前梯控状态与恒大不一致");
                                            bool result = LadderControl(liftid);//进入梯控

                                            if (result)
                                            {
                                                ModeRecord mode = new ModeRecord();
                                                mode.workmode = 0;
                                                mode.updatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                                mode.reason = "电梯状态和恒大平台下发不一致";
                                                InsertModeRecord(mode);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (ele_control == 1)
                                        {
                                            //bool result = ExitLadderControl(liftid);//退出梯控
                                        }
                                    }

                                    data += liftid.ToString("X").PadLeft(2, '0');
                                    if (elevatorPoint.Up == 1)
                                    {
                                        data += " 01";
                                    }
                                    else if (elevatorPoint.Down == 1)
                                    {
                                        data += " 02";
                                    }
                                    else if (elevatorPoint.Fault == 1)
                                    {
                                        data += " 80";
                                    }
                                    else if (elevatorPoint.Up == 0 && elevatorPoint.Down == 0)
                                    {
                                        data += " 00";
                                    }

                                    if (elevatorPoint.Open == 1)
                                    {
                                        data += " 10";
                                    }
                                    else if (elevatorPoint.Open == 1)
                                    {
                                        data += " 12";
                                    }
                                    else if (elevatorPoint.Close == 1)
                                    {
                                        data += " 13";
                                    }
                                    else
                                    {
                                        data += " 80";
                                    }

                                    if (elevatorPoint.PhysicalFloor == 0)
                                    {
                                        data += " 00 00";
                                    }
                                    else
                                    {
                                        List<int> show_floor_list = ToActFloorByPhy(elevatorPoint.PhysicalFloor);
                                        string value = string.Empty;
                                        if (show_floor_list[0] > 0)
                                        {
                                            value = "0000000" + Convert.ToString(show_floor_list[0], 2).PadLeft(9, '0');
                                        }
                                        else
                                        {
                                            value = "0000001" + Convert.ToString(Math.Abs(show_floor_list[0]), 2).PadLeft(9, '0');
                                        }
                                        data += " " + string.Format("{0:X}", Convert.ToInt32(value.Substring(0, 8), 2)).PadLeft(2, '0') + " " + string.Format("{0:X}", Convert.ToInt32(value.Substring(8, 8), 2)).PadLeft(2, '0');
                                    }
                                    StatusCmd = data;
                                    //副电梯，通过Tcp发送至主电梯
                                    if (!ismaster)
                                    {
                                        LogHelper.Log("电梯状态变更,发送给主梯");
                                        SlaveCmdSend(StatusCmd);
                                    }

                                    oldstatus_1 = newstatus;
                                }
                                else
                                {
                                    if (!ismaster)//数据状态与上一次相同，1s发送一次
                                    {
                                        LogHelper.Log("数据状态与上一次相同，1s发送一次");
                                        if (SlaveStatusCmd() > 1000)
                                        {
                                            SlaveCmdSend(StatusCmd);
                                        }
                                    }
                                    HDZHCurrentElevatorStatus currentElevator_old = new HDZHCurrentElevatorStatus();
                                    memoryCache.TryGetValue(liftid, out currentElevator_old);
                                    currentElevator_old.Update = DateTime.Now;
                                    memoryCache.Set(liftid, currentElevator_old);
                                }
                            }
                        }
                    }
                    SerialPortRecvTimerS0_1.Stop();
                }
                catch (Exception ex1)
                {
                    LogHelper.Log(ex1.ToString());
                }
            }
            catch (Exception)
            {
            }

        }

        public bool LadderControl(int devid)
        {
            if (ExceLadder(devid, 1))
            {
                sign_kt = -1;
                return true;
            }
            return true;
        }

        public bool ExceLadder(int devid, int value)
        {
            bool sendresult = SingleFloor(devid, 57, 1, value);
            if (sendresult)
            {
                Elevatormode = value;
                //电梯状态上报
                Report(devid);

                return true;
            }
            else
            {
                return false;
            }
        }

        public bool SingleFloor(int devid, int add, int count, int value)
        {
            try
            {
                string addhex = (add - 1).ToString("X").PadLeft(4, '0');
                string numhex = count.ToString("X").PadLeft(4, '0');
                string bytenum = (2 * count).ToString("X").PadLeft(2, '0');
                string cmd = "0000000" + value.ToString();
                LogHelper.Log(cmd);
                string strvalue = string.Format("{0:X}", Convert.ToInt32(cmd.Substring(0, 8), 2)).PadLeft(2, '0');
                string strcmd = devid.ToString("X").PadLeft(2, '0') + " 10 " + addhex.Substring(0, 2) + " " + addhex.Substring(2, 2) + " " + numhex.Substring(0, 2) + " " + numhex.Substring(2, 2) + " " + bytenum + " 00" + " " + strvalue;
                byte[] data = ToBytesSendDate(strcmd);
                byte[] crc = Crc18(data);
                strcmd += " " + crc[1].ToString("X").PadLeft(2, '0') + " " + crc[0].ToString("X").PadLeft(2, '0');
                LogHelper.Log("命令" + strcmd);
                cmdlist.Add(strcmd);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public void Report(int devid)
        {
            ElevatorPoint point = new ElevatorPoint();
            memoryCache.TryGetValue(devid, out point);

            Device elevator = new Device();
            if (point.falut == 1)
            {
                elevator.State = 2;
            }
            else
            {
                elevator.State = 1;
            }

            elevator.Floor = point.physicalfloor;

            if (point.up == 1)
            {
                elevator.Dicrection = 1;
            }
            else if (point.down == 1)
            {
                elevator.Dicrection = 2;
            }
            else
            {
                elevator.Dicrection = 0;
            }

            ElevatorDevReport(elevator);
        }

        /// <summary>
        /// 电梯设备状态上报
        /// </summary>
        public void ElevatorDevReport(Device dev)
        {
            if (!string.IsNullOrEmpty(subdevid))
            {
                dev.deviceID = subdevid;
                List<Device> list = new List<Device>();
                list.Add(dev);
                ElevatorEquipment elevator = new ElevatorEquipment();
                elevator.Command = "FAC_UPLOAD_DEV_STATUS";
                elevator.Data = list;
                string str = JsonConvert.SerializeObject(elevator);
                string zs = IntToHex(count).PadLeft(8, '0'); ;
                string datazs = zs.Substring(0, 2) + " " + zs.Substring(2, 2) + " " + zs.Substring(4, 2) + " " + zs.Substring(6, 2);
                string strCmd = StringToHex(str);
                int num = strCmd.Split(' ').Length;
                string datalength = IntToHex(num).PadLeft(8, '0');
                string length = datalength.Substring(0, 2) + " " + datalength.Substring(2, 2) + " " + datalength.Substring(4, 2) + " " + datalength.Substring(6, 2);
                string crc = CRCCalc(strCmd);
                strCmd = "48 44 58 4D " + StringToHex(devid) + " " + StringToHex("00000000000000000000") + " 00 " + datazs + " " + length + " 00 00 " + crc + " " + strCmd;
                SendMsg(strCmd, true, false);
            }
        }

        public bool SendMsg(string str, bool isinitiative, bool isRegCmd)
        {
            try
            {
                string senddata = string.Format(@"{0}", str);
                bool result = false;

                if (hd_server_flag)
                {
                    if (device_register_flag)
                    {
                        try
                        {
                            server.Send(HexStringToByteArray(senddata));
                        }
                        catch
                        {
                            device_register_flag = false;
                            hd_server_flag = false;
                            return false;
                        }
                        if (isinitiative)
                        {
                            if (count < 2147483647)
                            {
                                count++;
                            }
                            else
                            {
                                count = 1;
                            }
                        }
                        return true;
                    }

                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public string CRCCalc(string data)
        {
            string[] datas = data.Split(' ');
            List<byte> bytedata = new List<byte>();

            foreach (string str in datas)
            {
                bytedata.Add(byte.Parse(str, System.Globalization.NumberStyles.AllowHexSpecifier));
            }
            byte[] crcbuf = bytedata.ToArray();
            //计算并填写CRC校验码
            int crc = 0xffff;
            int len = crcbuf.Length;

            for (int j = 0; j < len; j++)
            {
                crc = ((crc >> 8) | (crc << 8)) & 0xffff;
                crc ^= (crcbuf[j] & 0xff);
                crc ^= ((crc & 0xff) >> 4);
                crc ^= (crc << 12) & 0xffff;
                crc ^= ((crc & 0xff) << 5) & 0xffff;
            }
            crc = crc & 0xffff;

            string[] redata = new string[2];
            redata[1] = Convert.ToString((byte)((crc >> 8) & 0xff), 16);
            redata[0] = Convert.ToString((byte)((crc & 0xff)), 16);
            string a = redata[1].ToString().PadLeft(2, '0') + " " + redata[0].ToString().PadLeft(2, '0');
            return a.ToUpper();
        }

        public string StringToHex(string strEncode)
        {
            string strReturn = "";
            foreach (short shortx in strEncode.ToCharArray())
            {
                strReturn += shortx.ToString("X2") + " ";
            }
            strReturn = strReturn.TrimEnd(' ').ToUpper();
            return strReturn;
        }

        public string IntToHex(int num)
        {
            string result = "";
            result = Convert.ToString(num, 16).ToUpper();
            return result;
        }

        public byte[] ToBytesSendDate(string str)
        {
            List<byte> result = new List<byte>();
            if (str.Contains(" "))
            {
                string[] strs = str.Trim().Split(' ');
                foreach (string s in strs)
                {
                    result.Add(Convert.ToByte(s.Trim(), 16));
                }
            }
            else
            {
                result.Add(Convert.ToByte(str, 16));
            }
            return result.ToArray();
        }

        public HDZHCurrentElevatorStatus ParsingData(int devid, byte[] crcdata)
        {
            HDZHCurrentElevatorStatus currentElevatorStatus = new HDZHCurrentElevatorStatus();
            try
            {
                //电梯物理楼层 40001
                currentElevatorStatus.PhysicalFloor = Convert.ToInt32(crcdata[4].ToString().PadLeft(2, '0'));
                byte[] floorbuffer = new byte[2];
                floorbuffer[0] = crcdata[5];
                floorbuffer[1] = crcdata[6];
                string _showfloor = HexToString(floorbuffer);
                //电梯显示楼层 40002
                if (floorbuffer[0] == 0 && floorbuffer[1] == 0)
                {
                    currentElevatorStatus.DisplayFloor = "0";
                }
                else
                {
                    if (_showfloor.Substring(0, 1) == "0")
                    {
                        currentElevatorStatus.DisplayFloor = _showfloor.Substring(1, 1);
                    }
                    else
                    {
                        currentElevatorStatus.DisplayFloor = _showfloor;
                    }
                }
                //电梯运行点位40003
                string point_run_h = Convert.ToString(crcdata[7], 2).PadLeft(8, '0');
                string point_run_l = Convert.ToString(crcdata[8], 2).PadLeft(8, '0');
                currentElevatorStatus.Up = Convert.ToInt32(point_run_l.Substring(7, 1));
                currentElevatorStatus.Down = Convert.ToInt32(point_run_l.Substring(6, 1));
                currentElevatorStatus.Open = Convert.ToInt32(point_run_l.Substring(5, 1));
                currentElevatorStatus.Close = Convert.ToInt32(point_run_l.Substring(4, 1));
                currentElevatorStatus.Fault = Convert.ToInt32(point_run_l.Substring(3, 1));
                currentElevatorStatus.Control = Convert.ToInt32(point_run_l.Substring(2, 1));
                currentElevatorStatus.Update = DateTime.Now;
                string state = JsonConvert.SerializeObject(currentElevatorStatus);
                HDZHCurrentElevatorStatus currentElevator_old = new HDZHCurrentElevatorStatus();
                memoryCache.TryGetValue(liftid, out currentElevator_old);
                if (currentElevator_old != null)
                {
                    if (currentElevator_old.Fault != currentElevatorStatus.Fault)
                    {
                        if (currentElevatorStatus.Fault == 1)
                        {
                            LogHelper.Log("电梯故障");
                        }
                        else if (currentElevatorStatus.Fault == 0)
                        {
                            LogHelper.Log("电梯恢复故障");
                        }
                    }
                }
                ele_control = currentElevatorStatus.Control;
                currentElevatorStatus.Update = DateTime.Now;
                memoryCache.Set(devid, currentElevatorStatus);
                return currentElevatorStatus;
            }
            catch (Exception e)
            {
                LogHelper.Log(e.ToString());
                return currentElevatorStatus;
            }
        }

        public void SlaveCmdSend(string cmd)
        {
            //lock (slavesendlocker)
            //{
            //    SendToServer(cmd);
            //}
        }

        public List<int> ToActFloorByPhy(int phy_floor)
        {
            List<int> list = new List<int>();
            for (int i = 0; i < phy_list.Count; i++)
            {
                if (phy_list[i] == phy_floor)
                {
                    list.Add(act_list[i]);
                }
            }
            return list;
        }

        public int SlaveStatusCmd()
        {
            int i = 9999;
            if (statussend.Year == 1)
            {
                return i;
            }
            else
            {
                TimeSpan ts1 = new TimeSpan(DateTime.Now.Ticks);
                TimeSpan ts2 = new TimeSpan(statussend.Ticks);
                TimeSpan ts3 = ts1.Subtract(ts2).Duration();
                i = (int)ts3.TotalMilliseconds;
            }

            return i;
        }

        public bool InsertModeRecord(ModeRecord modeRecord)
        {
            try
            {
                DeviceDAL da = new DeviceDAL();
                da.InsertModeRecord(modeRecord);
                return true;
            }
            catch
            {
                return false;
            }
        }

        #endregion

        #region CRC校验
        public byte[] Crc18(byte[] buffer, int start = 0, int len = 0)
        {
            if (buffer == null || buffer.Length == 0) return null;
            if (start < 0) return null;
            if (len == 0) len = buffer.Length - start;
            int length = start + len;
            if (length > buffer.Length) return null;
            ushort crc = 0xFFFF;// Initial value
            for (int i = start; i < length; i++)
            {
                crc ^= buffer[i];
                for (int j = 0; j < 8; j++)
                {
                    if ((crc & 1) > 0)
                        crc = (ushort)((crc >> 1) ^ 0xA001);// 0xA001 = reverse 0x8005
                    else
                        crc = (ushort)(crc >> 1);
                }
            }
            byte[] ret = BitConverter.GetBytes(crc);
            Array.Reverse(ret);
            return ret;
        }
        #endregion

        #region byte转十六进制
        public string ToHexs(byte[] data)
        {
            if (data.Length <= 0) return "";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sb.Append(data[i].ToString("X2"));
                sb.Append(" ");
            }
            string str = sb.ToString();
            return str.Substring(0, str.Length - 1);
        }
        #endregion

        #region 恒大平台注册
        public void HDConnect()
        {
            devinfo.mac = GetLocalMac();
            devinfo.localIP = GetLocalIP();
            subdevid = "3063" + devinfo.mac.Replace("-", "") + devinfo.liftid.ToString("X").PadLeft(4, '0');
            Task t = Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    try
                    {
                        if (!hd_server_flag)
                        {

                        }
                        else
                        {
                            if (device_register_flag)
                            {

                            }
                        }
                    }
                    catch (Exception ex)
                    {

                    }

                    Task.Delay(1000).Wait();
                }
            });
        }

        public bool ConnectToHD(string serverip, int port)
        {
            bool result = false;

            result = ConnectServer(serverip, port);

            return result;
        }

        public bool ConnectServer(string serverIP, int port)
        {
            try
            {
                server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                server.Connect(serverIP, port);
                thread = new Thread(StartReceive);
                thread.Start(server);
                return true;
            }
            catch (Exception e)
            {
                // logPrint.Log("连接恒大异常");
                return false;
            }
        }

        public void StartReceive(object obj)
        {
            byte[] buffer = new byte[2048];
            int length = 0;
            while (true)
            {
                try
                {
                    length = server.Receive(buffer);
                    if (length == 0)
                    {
                        break;
                    }
                    else
                    {
                        if (buffer[0] == 0x48 && buffer[1] == 0x44 && buffer[2] == 0x58 && buffer[3] == 0x4D)
                        {
                            List<byte> data = new List<byte>();

                            string strvalue = buffer[49].ToString("X").PadLeft(2, '0') + buffer[50].ToString("X").PadLeft(2, '0') + buffer[51].ToString("X").PadLeft(2, '0') + buffer[52].ToString("X").PadLeft(2, '0');
                            int value = int.Parse(strvalue, System.Globalization.NumberStyles.HexNumber) + 57;
                            string pack_hex = buffer[45].ToString("X2").PadLeft(2, '0') + buffer[46].ToString("X2").PadLeft(2, '0') + buffer[47].ToString("X2").PadLeft(2, '0') + buffer[48].ToString("X2").PadLeft(2, '0');
                            int packnum = Convert.ToInt32(pack_hex, 16);
                            for (int j = 0; j < length; j++)
                            {
                                if (j < value)
                                {
                                    data.Add(buffer[j]);
                                }
                            }
                            try
                            {
                                ReceiveData message = AnalysisType(data);
                                if (message != null)
                                {
                                    //下发凭证
                                    if (message.Command.ToUpper() == "COM_LOAD_CERTIFICATE")
                                    {
                                        CardInfo card = GetVoucherInfo(message.Data[0].ToString());
                                        if (card != null)
                                        {
                                            bool result = false;
                                            VoucherInfo voucher = QueryVoucher(card);
                                            if (voucher == null)
                                            {
                                                result = InsertVoucher(card);
                                            }
                                            else
                                            {
                                                result = UpdateVoucher(card);
                                            }

                                            Message replay = new Message();
                                            replay.Command = "COM_LOAD_CERTIFICATE";
                                            if (result)
                                            {
                                                replay.Result = 0;
                                            }
                                            else
                                            {
                                                replay.Result = 1;
                                            }
                                            string str = JsonConvert.SerializeObject(replay);
                                            string datazs = string.Format("{0} {1} {2} {3}", data[45].ToString("X").PadLeft(2, '0'), data[46].ToString("X").PadLeft(2, '0'), data[47].ToString("X").PadLeft(2, '0'), data[48].ToString("X").PadLeft(2, '0'));
                                            string strCmd = StringToHex(str);
                                            int num = strCmd.Split(' ').Length;
                                            string datalength = IntToHex(num).PadLeft(8, '0').ToUpper();
                                            string length1 = datalength.Substring(0, 2) + " " + datalength.Substring(2, 2) + " " + datalength.Substring(4, 2) + " " + datalength.Substring(6, 2);
                                            string crc = CRCCalc(strCmd);
                                            strCmd = "48 44 58 4D " + StringToHex(devid) + " " + StringToHex("00000000000000000000") + " 00 " + datazs + " " + length1 + " 00 00 " + crc + " " + strCmd;
                                            LogHelper.Log(strCmd);
                                            SendMsg(strCmd, false, false);
                                        }
                                    }
                                    //删除凭证
                                    else if (message.Command.ToUpper() == "COM_DELETE_CERTIFICATE")
                                    {
                                        CardInfo card = GetVoucherInfo(message.Data[0].ToString());
                                        if (card != null)
                                        {
                                            bool result = DelVoucher(card);

                                            Message replay = new Message();
                                            replay.Command = "COM_DELETE_CERTIFICATE";
                                            if (result)
                                            {
                                                replay.Result = 0;
                                            }
                                            else
                                            {
                                                replay.Result = 1;
                                            }
                                            string str = JsonConvert.SerializeObject(replay);
                                            string datazs = string.Format("{0} {1} {2} {3}", data[45].ToString("X").PadLeft(2, '0'), data[46].ToString("X").PadLeft(2, '0'), data[47].ToString("X").PadLeft(2, '0'), data[48].ToString("X").PadLeft(2, '0'));
                                            string strCmd = StringToHex(str);
                                            int num = strCmd.Split(' ').Length;
                                            string datalength = IntToHex(num).PadLeft(8, '0');
                                            string length1 = datalength.Substring(0, 2) + " " + datalength.Substring(2, 2) + " " + datalength.Substring(4, 2) + " " + datalength.Substring(6, 2);
                                            string crc = CRCCalc(strCmd);
                                            strCmd = "48 44 58 4D " + StringToHex(devid) + " " + StringToHex("00000000000000000000") + " 00 " + datazs + " " + length1 + " 00 00 " + crc + " " + strCmd;
                                            SendMsg(strCmd, false, false);

                                        }
                                    }
                                    //清除所有凭证
                                    else if (message.Command.ToUpper() == "COM_DELETE_CERTIFICATE_IN_BATCH")
                                    {
                                        CardInfo card = GetVoucherInfo(message.Data[0].ToString());
                                        if (card != null)
                                        {
                                            bool result = DelAllTypeVoucher(card.CredenceType);

                                            Message replay = new Message();
                                            replay.Command = "COM_DELETE_CERTIFICATE_IN_BATCH";
                                            if (result)
                                            {
                                                replay.Result = 0;
                                            }
                                            else
                                            {
                                                replay.Result = 1;
                                            }
                                            string str = JsonConvert.SerializeObject(replay);
                                            string datazs = string.Format("{0} {1} {2} {3}", data[45].ToString("X").PadLeft(2, '0'), data[46].ToString("X").PadLeft(2, '0'), data[47].ToString("X").PadLeft(2, '0'), data[48].ToString("X").PadLeft(2, '0'));
                                            string strCmd = StringToHex(str);
                                            int num = strCmd.Split(' ').Length;
                                            string datalength = IntToHex(num).PadLeft(8, '0');
                                            string length1 = datalength.Substring(0, 2) + " " + datalength.Substring(2, 2) + " " + datalength.Substring(4, 2) + " " + datalength.Substring(6, 2);
                                            string crc = CRCCalc(strCmd);
                                            strCmd = "48 44 58 4D " + StringToHex(devid) + " " + StringToHex("00000000000000000000") + " 00 " + datazs + " " + length1 + " 00 00 " + crc + " " + strCmd;

                                            SendMsg(strCmd, false, false);
                                        }
                                    }
                                    //参数读取
                                    else if (message.Command.ToUpper() == "COM_READ_PARAMETER")
                                    {
                                        Parameter.deviceID = devid;
                                        Parameter.workMode = GetMode().ToString();
                                        ParameterReadMessage replay = new ParameterReadMessage();
                                        replay.Command = "COM_READ_PARAMETER";
                                        replay.Data = Parameter;
                                        string str = JsonConvert.SerializeObject(replay);
                                        string datazs = string.Format("{0} {1} {2} {3}", data[45].ToString("X").PadLeft(2, '0'), data[46].ToString("X").PadLeft(2, '0'), data[47].ToString("X").PadLeft(2, '0'), data[48].ToString("X").PadLeft(2, '0'));
                                        string strCmd = StringToHex(str);
                                        int num = strCmd.Split(' ').Length;
                                        string datalength = IntToHex(num).PadLeft(8, '0');
                                        string length1 = datalength.Substring(0, 2) + " " + datalength.Substring(2, 2) + " " + datalength.Substring(4, 2) + " " + datalength.Substring(6, 2);
                                        string crc = CRCCalc(strCmd);
                                        strCmd = "48 44 58 4D " + StringToHex(devid) + " " + StringToHex("00000000000000000000") + " 00 " + datazs + " " + length1 + " 00 00 " + crc + " " + strCmd;

                                        SendMsg(strCmd, false, false);
                                    }
                                    //参数设置
                                    else if (message.Command.ToUpper() == "COM_SETTING_PARAMETERS")
                                    {
                                        ParameterSet parameterSet = GetParameterSet(message.Data[0].ToString());
                                        if (parameterSet != null)
                                        {
                                            devinfo = GetDevInfo();
                                            Parameter.fileServerUrl = parameterSet.fileServerUrl;
                                            Parameter.ntpServer = parameterSet.ntpServer;
                                            Parameter.httpUserName = parameterSet.httpUserName;
                                            Parameter.httpPassword = parameterSet.httpPassword;
                                            Parameter.liftCarNumber = parameterSet.liftCarNumber;
                                            Parameter.workMode = parameterSet.workMode;
                                            Parameter.lightMode = parameterSet.lightMode;
                                            Parameter.intervalTime = parameterSet.intervalTime;
                                            reporttime = Convert.ToInt32(parameterSet.intervalTime);

                                            LogHelper.Log("恒大下发梯控模式" + parameterSet.workMode.ToString());
                                            int mode = 0;
                                            if (parameterSet.workMode == "0")
                                            {
                                                mode = 1;
                                            }
                                            UpdateLightMode(Convert.ToInt32(parameterSet.lightMode));
                                            UpdateHdStatus(mode);
                                            HDTK(mode, "恒大参数设置");

                                            if (parameterSet.ntpServer != devinfo.ntpserver)
                                            {
                                                RaspberryPie pie = new RaspberryPie();
                                            }

                                            Message replay = new Message();
                                            replay.Command = "COM_SETTING_PARAMETERS";
                                            if (UpdateParameter(parameterSet))
                                            {
                                                replay.Result = 0;
                                            }
                                            else
                                            {
                                                replay.Result = 1;
                                            }
                                            string str = JsonConvert.SerializeObject(replay);
                                            string datazs = string.Format("{0} {1} {2} {3}", data[45].ToString("X").PadLeft(2, '0'), data[46].ToString("X").PadLeft(2, '0'), data[47].ToString("X").PadLeft(2, '0'), data[48].ToString("X").PadLeft(2, '0')); string strCmd = StringToHex(str);
                                            int num = strCmd.Split(' ').Length;
                                            string datalength = IntToHex(num).PadLeft(8, '0');
                                            string length1 = datalength.Substring(0, 2) + " " + datalength.Substring(2, 2) + " " + datalength.Substring(4, 2) + " " + datalength.Substring(6, 2);
                                            string crc = CRCCalc(strCmd);
                                            strCmd = "48 44 58 4D " + StringToHex(devid) + " " + StringToHex("00000000000000000000") + " 00 " + datazs + " " + length1 + " 00 00 " + crc + " " + strCmd;

                                            SendMsg(strCmd, false, false);
                                        }
                                    }
                                    //批量查询轿厢状态
                                    else if (message.Command.ToUpper() == "FAC_LIFT_BA_STATUS")
                                    {

                                        StatusQuery statusQuery = GetCarStatusQuery(message.Data[0].ToString());
                                        if (statusQuery.carIDList.Contains(devinfo.liftid.ToString().PadLeft(2, '0')))
                                        {
                                            QueryAllCarStatus();
                                        }
                                    }
                                    //目录查询
                                    else if (message.Command.ToUpper() == "COM_QUERY_DIR")
                                    {
                                        CatalogueData msgdata = new CatalogueData();
                                        msgdata.Command = "COM_QUERY_DIR";
                                        CatalogueInfo catalogue = new CatalogueInfo();
                                        catalogue.deviceID = subdevid;
                                        catalogue.name = "OTIS" + devinfo.liftid.ToString();
                                        catalogue.subDeviceType = 3036;
                                        catalogue.version = version_1;
                                        List<CatalogueInfo> list = new List<CatalogueInfo>();
                                        list.Add(catalogue);
                                        msgdata.Data = list;
                                        string datazs = string.Format("{0} {1} {2} {3}", data[45].ToString("X").PadLeft(2, '0'), data[46].ToString("X").PadLeft(2, '0'), data[47].ToString("X").PadLeft(2, '0'), data[48].ToString("X").PadLeft(2, '0'));
                                        string str = JsonConvert.SerializeObject(msgdata);
                                        string strCmd = StringToHex(str);
                                        int num = strCmd.Split(' ').Length;
                                        string datalength = IntToHex(num).PadLeft(8, '0');
                                        string length1 = datalength.Substring(0, 2) + " " + datalength.Substring(2, 2) + " " + datalength.Substring(4, 2) + " " + datalength.Substring(6, 2);
                                        string crc = CRCCalc(strCmd);
                                        strCmd = "48 44 58 4D " + StringToHex(devid) + " " + StringToHex("00000000000000000000") + " 00 " + datazs + " " + length1 + " 00 00 " + crc + " " + strCmd;

                                        SendMsg(strCmd, false, false);
                                    }
                                    //人脸识别
                                    else if (message.Command.ToUpper() == "ISSUE_COMMAND")
                                    {
                                        CmdMessage cmd = GetCmdInfo(message.Data[0].ToString());
                                        if (cmd != null)
                                        {
                                            SendCmdToTK(cmd.Cmd, cmd.DevNo, cmd.Address, cmd.DataLen);
                                        }
                                    }
                                    else
                                    {
                                        if (dic_data.ContainsKey(packnum))
                                        {
                                            dic_data.Remove(packnum);
                                        }
                                        dic_data.Add(packnum, data);
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                continue;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    continue;
                }
            }
        }

        public bool SendCmdToTK(string cmd, int devid, int add, int count)
        {
            try
            {
                cmdlist.Add(cmd);

                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 批量查询
        /// </summary>
        public bool QueryAllCarStatus()
        {
            CarStatus carStatus = new CarStatus();
            ElevatorPoint point = new ElevatorPoint();
            memoryCache = GetStatusMemory();
            memoryCache.TryGetValue(devinfo.liftid, out point);
            ElevatorStatus status = new ElevatorStatus();
            if (point != null)
            {
                status.deviceID = subdevid;
                status.carID = devinfo.liftid.ToString().PadLeft(2, '0');
                status.physicalfloor = point.physicalfloor;
                status.displayfloor = point.Showfloor;
                if (point.up == 1)
                {
                    status.status = "01";
                }
                else if (point.down == 1)
                {
                    status.status = "02";
                }
                else
                {
                    status.status = "00";
                }

                if (point.frontdooropening == 1)
                {
                    status.doorStatus = "10";
                }
                else if (point.frontdooropened == 1)
                {
                    status.doorStatus = " 11";
                }
                else if (point.frontdoorcloseing == 1)
                {
                    status.doorStatus = " 12";
                }
                else if (point.frontdoorclosed == 1)
                {
                    status.doorStatus = " 13";
                }

                if (point.falut == 1)
                {
                    status.errorStatus = 1;
                }
                else
                {
                    status.errorStatus = 0;
                }
            }

            carStatus.Command = "FAC_LIFT_BA_STATUS";
            carStatus.Data.statusList.Add(status);
            string str = JsonConvert.SerializeObject(carStatus);
            string zs = IntToHex(count).PadLeft(8, '0'); ;
            string datazs = zs.Substring(0, 2) + " " + zs.Substring(2, 2) + " " + zs.Substring(4, 2) + " " + zs.Substring(6, 2);
            string strCmd = StringToHex(str);
            int num = strCmd.Split(' ').Length;
            string datalength = IntToHex(num).PadLeft(8, '0');
            string length = datalength.Substring(0, 2) + " " + datalength.Substring(2, 2) + " " + datalength.Substring(4, 2) + " " + datalength.Substring(6, 2);
            string crc = CRCCalc(strCmd);
            strCmd = "48 44 58 4D " + StringToHex(devid) + " " + StringToHex("00000000000000000000") + " 00 " + datazs + " " + length + " 00 00 " + crc + " " + strCmd;
            if (SendMsg(strCmd, true, false))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public MemoryCache GetStatusMemory()
        {
            return memoryCache;
        }

        #region 凭证操作
        public bool InsertVoucher(CardInfo cardInfo)
        {
            string strSql = string.Format(@"INSERT INTO cardinfo(cardID,StartTime,OverTime,subDeviceID,UserType,CredenceType,username,UUID,elevatorAuthFloor)VALUES('{0}','{1}','{2}','{3}',{4},{5},'{6}','{7}','{8}')", cardInfo.credenceNo, cardInfo.startTime, cardInfo.endTime, cardInfo.subDeviceID, 3, cardInfo.CredenceType, "", cardInfo.userID, string.Join(",", cardInfo.elevatorAuthFloor));
            CommFN<CardInfo> fn = new CommFN<CardInfo>();
            return fn.ExecFN(strSql);
        }

        public VoucherInfo QueryVoucher(CardInfo cardInfo)
        {
            string strSql = string.Format(@"SELECT * FROM cardinfo WHERE UUID='{0}'", cardInfo.userID);
            CommFN<VoucherInfo> fn = new CommFN<VoucherInfo>();
            return fn.GetData(strSql);
        }

        public bool UpdateVoucher(CardInfo cardInfo)
        {
            string strSql = string.Format(@"UPDATE cardinfo SET cardID='{0}',StartTime='{1}',OverTime='{2}',subDeviceID='{3}',UserType='{4}',CredenceType={5},username='{6}',elevatorAuthFloor='{7}' WHERE UUID='{8}'", cardInfo.credenceNo, cardInfo.startTime, cardInfo.endTime, cardInfo.subDeviceID, 3, cardInfo.CredenceType, "", string.Join(",", cardInfo.elevatorAuthFloor), cardInfo.userID);
            CommFN<VoucherInfo> fn = new CommFN<VoucherInfo>();
            return fn.ExecFN(strSql);
        }

        public bool DelVoucher(CardInfo cardInfo)
        {
            string strSql = string.Format(@"DELETE FROM cardinfo WHERE UUID='{0}'", cardInfo.userID);
            CommFN<VoucherInfo> fn = new CommFN<VoucherInfo>();
            return fn.ExecFN(strSql);
        }

        public bool DelAllTypeVoucher(int type)
        {
            string strSql = "DELETE FROM cardinfo";
            CommFN<VoucherInfo> fn = new CommFN<VoucherInfo>();
            return fn.ExecFN(strSql);
        }

        #endregion
        public bool HDTK(int value, string type)
        {
            if (value == 0)
            {
                if (TkControl())//授权
                {
                    ModeRecord modeRecord = new ModeRecord();
                    modeRecord.workmode = value;
                    modeRecord.reason = type;
                    modeRecord.updatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    InsertModeRecord(modeRecord);
                    return true;
                }
            }
            else
            {
                if (ExitLadderControl(liftid))//退出梯控
                {
                    ModeRecord modeRecord = new ModeRecord();
                    modeRecord.workmode = value;
                    modeRecord.reason = type;
                    modeRecord.updatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    InsertModeRecord(modeRecord);
                    return true;
                }
            }


            return false;
        }

        #region 参数操作
        public bool UpdateParameter(ParameterSet para)
        {
            string strSql = string.Format(@"UPDATE devinfo SET intervalTime={0},ntpserver='{1}'", Convert.ToInt32(para.intervalTime), para.ntpServer);
            CommFN<CardInfo> fn = new CommFN<CardInfo>();
            return fn.ExecFN(strSql);
        }
        #endregion

        public bool UpdateLight(int mode)
        {
            string strSql = "UPDATE devinfo SET lightmode=" + mode;
            CommFN<DevInfo> fn = new CommFN<DevInfo>();
            return fn.ExecFN(strSql);
        }

        public bool ExitLadderControl(int devid)
        {
            return ExceLadder(devid, 0);
        }

        public bool TkControl()
        {
            if (ExceLadder(liftid, 1))
            {
                hd_kt = -1;
                return true;
            }
            return true;
        }

        public bool UpdateHdStatus(int value)
        {
            try
            {
                if (UpdateModeStatus(value))
                {
                    if (value == 0)
                    {
                        TcpAuthorize = true;
                    }
                    else if (value == 1)
                    {
                        TcpAuthorize = false;
                    }
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

        public bool UpdateModeStatus(int mode)
        {
            try
            {
                string strSql = "UPDATE devinfo SET workmode=" + mode + ",updatetime='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'";
                CommFN<DevInfo> fn = new CommFN<DevInfo>();
                return fn.ExecFN(strSql);
            }
            catch
            {
                return false;
            }
        }

        public bool UpdateLightMode(int value)
        {
            try
            {
                if (UpdateLight(value))
                {
                    light = value;
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

        public DevInfo GetDevInfo()
        {
            try
            {
                string strSql = "SELECT * FROM devinfo";
                CommFN<DevInfo> fn = new CommFN<DevInfo>();
                return fn.GetData(strSql);
            }
            catch(Exception ex)
            {
                return null;
            }
        }

        public int GetMode()
        {
            if (ele_control == 1)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }

        #region 数据解析  

        /// <summary>
        /// 解析类型
        /// </summary>
        public ReceiveData AnalysisType(List<byte> data1)
        {
            ReceiveData message;
            try
            {
                List<byte> data = data1.GetRange(57, data1.Count - 57);
                string result = string.Empty;
                result = Encoding.GetEncoding("utf-8").GetString(data.ToArray(), 0, data.Count);
                message = JsonConvert.DeserializeObject<ReceiveData>(result);
            }
            catch
            {
                return null;
            }
            return message;
        }

        /// <summary>
        /// 凭证解析
        /// </summary>
        public CardInfo GetVoucherInfo(string data)
        {
            CardInfo cardInfo;
            try
            {
                cardInfo = JsonConvert.DeserializeObject<CardInfo>(data);
            }
            catch
            {
                LogHelper.Log("凭证为空");
                return null;
            }
            return cardInfo;
        }

        /// <summary>
        /// 参数设置解析
        /// </summary>
        public ParameterSet GetParameterSet(string data)
        {
            ParameterSet para;
            try
            {
                para = JsonConvert.DeserializeObject<ParameterSet>(data);
            }
            catch
            {
                return null;
            }
            return para;
        }

        /// <summary>
        /// 状态查询解析
        /// </summary>
        public StatusQuery GetCarStatusQuery(string data)
        {
            StatusQuery status;
            try
            {
                status = JsonConvert.DeserializeObject<StatusQuery>(data);
            }
            catch
            {
                return null;
            }
            return status;
        }

        /// <summary>
        /// 命令解析
        /// </summary>
        public CmdMessage GetCmdInfo(string data)
        {
            CmdMessage message;
            try
            {
                message = JsonConvert.DeserializeObject<CmdMessage>(data);
            }
            catch
            {
                return null;
            }
            return message;
        }

        /// <summary>
        /// 解析回复数据
        /// </summary>
        public InitReplayData AnalysisReplay(List<byte> data1)
        {
            InitReplayData message;
            try
            {
                List<byte> data = data1.GetRange(57, data1.Count - 57);
                string result = string.Empty;
                result = Encoding.GetEncoding("utf-8").GetString(data.ToArray(), 0, data.Count);
                message = JsonConvert.DeserializeObject<InitReplayData>(result);
            }
            catch
            {
                return null;
            }
            return message;
        }

        #endregion

        public string GetLocalMac()
        {
            string macAddress = "";
            try
            {
                foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
                {
                    if (nic.OperationalStatus == OperationalStatus.Up)
                    {
                        macAddress = nic.GetPhysicalAddress().ToString();
                        IPInterfaceProperties ipProperties = nic.GetIPProperties();
                        UnicastIPAddressInformation curIP = ipProperties.UnicastAddresses[0];
                        string ip = curIP.Address.ToString();
                        string mask = curIP.IPv4Mask.ToString();
                        string server = ipProperties.GatewayAddresses[0].Address.ToString();
                        break;
                    }
                }
                return macAddress;
            }
            catch
            {
                return "";
            }
        }

        public string GetLocalIP()
        {
            string localIP = string.Empty;
            try
            {
                using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
                {
                    socket.Connect("8.8.8.8", 65530);
                    IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
                    localIP = endPoint.Address.ToString();
                }
                return localIP;
            }
            catch
            {
                return "";
            }
        }
        #endregion

        public string HexToString(byte[] buffer)
        {
            // 将 byte数组 解码成 字符串：
            string getData = Encoding.Default.GetString(buffer);
            return getData;
        }

        public static byte[] HexStringToByteArray(string s)
        {
            s = s.Replace(" ", "");
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < s.Length; i += 2)
                buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
            return buffer;
        }

    }
}
